import React from 'react'
import { connect } from 'dva'
import QueryString from 'querystring'
import Nav from '../components/Nav'
import Header from '../components/Header'
import Commodity from '../components/Commodity'



class Index extends React.Component {

    componentDidMount() {
        const { dispatch, location, user } = this.props
        
        let urlParam = location.search
        urlParam = urlParam.replace('?', '')
        urlParam = QueryString.parse(urlParam)

        // 已经登录
        if (user.user.openid) {
            return
        }
        new Promise((resolve, reject) => {
            dispatch({
                type: 'user/login',
                payload: urlParam.code,
                resolve, reject
            })
            dispatch({
                type: 'commodity/getAll'
            })
        })
        .then(() => {
            dispatch({
                type: 'user/findAddress',
            })
        })
    }

    pay = () =>{
        const { dispatch, user } = this.props
        // console.log(
        //     'openid: ',
        //     user.user.openid
        // )
        dispatch({
            type: 'user/pay',
            payload: user.user.openid
        })
    }

    rednerCommodityList = () => {
        const { commodity } = this.props
        return (
            <div className='commodityList'>
                {
                    commodity.list.map(item => {
                        return (
                            <Commodity 
                                key={item._id}
                                data={item}
                            />
                        )
                    })
                }
            </div>
        )
    }

    render() {
        return (
            <div>
                <Header />
                {this.rednerCommodityList()}

                <Nav />
            </div>
        )
    }
}

const mapState = state => ({
    user: state.user,
    commodity: state.commodity
})

export default connect(mapState)(Index)
